// pages/mine/mine.js
var rightMusicUrl = 'https://channel.kxqianbao.com/ok.mp3'//回答正确
var errorMusicUrl = 'https://channel.kxqianbao.com/fail.mp3'//回答错误
var countDownMusicUrl = 'https://channel.kxqianbao.com/timelock.mp3'//超时
var app = getApp()
var url = app.basicsUrl();
Page({
  data: {
    id: '',
    hongBaoId: '',
    gameId: '',
    count: 1, //第几次挑战
    toughType: 3, //难度系数
    hongBaoHardType: 'hard',
    progressWidth: 0, //进度条宽度
    step: 185,//步长
    stepCount: 0,//进度条
    totalTime: 10,//倒计时
    timer: '',
    questionNum: 1, //题号
    randomArrary: [],
    questionCollect: [],
    questionInfo: { //展示的题
      question: '',
      answer: ''
    },
    isTrue: 'initial',  //选项样式
    tapId: -1,  //点击的下标
    isTransparentShow: false, //点击后是否让遮罩层显示
    hasPickMoney: false,
    money: 0,
    msg: '',
    tokenKey: "",
    token: "",
    openId: "",
    questionType:""
  },//随机题
  Random: function () {
    var that = this;
    var arr = that.data.randomArrary;
    var questionType = that.data.questionType;//题目类型
    var questionCollect = that.data.questionCollect;
    var length = questionCollect.length;
    var getAccordQuestion=[];//获取符合条件的题目
    for(var i = 0; i < length;i++){
      if (questionCollect[i]['questionType'] == questionType){
        getAccordQuestion.push(questionCollect[i])
      }
    }
    
    var index = parseInt(Math.random() * getAccordQuestion.length);
    //防止出现同样的题
    if (getAccordQuestion.indexOf(index) == -1) {
      arr.push(index);
      that.setData({
        randomArrary: arr,
        questionInfo: getAccordQuestion[index],
        isTransparentShow: false
      })
      var ans = "questionInfo.answer";
      that.setData({
        [ans]: [getAccordQuestion[index].ans1, getAccordQuestion[index].ans2, getAccordQuestion[index].ans3]
      })
    } else {
      that.Random();
    }
  },//点击选项
  answerTap: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var stepCount = that.data.stepCount;//进度条
    var step = that.data.step;//步长
    var questionNum = that.data.questionNum;//题号
    clearInterval(that.data.timer)
    that.setData({
      tapId: id,
      totalTime: 10,
      isTransparentShow: true
    })
    if (id == that.data.questionInfo.trueAns) {
      clearInterval(that.data.timer)
      that.playMusic(rightMusicUrl);
      that.setData({
        isTrue: 'correct',
        stepCount: ++stepCount
      })
      that.timeCount();
      //全部答对,游戏成功
      if ((stepCount) * step >= '555') {
        clearInterval(that.data.timer);
        wx.request({
          url: url + 'authorized/pickHongBao',
          data: {
            hongBaoId: that.data.hongBaoId,
            gameId: that.data.id,
            tokenKey: that.data.tokenKey,
            token: that.data.token,
            openId: that.data.openId
          },
          success: function (res) {
            var data = res.data.data;
            wx.redirectTo({
              url: '../../pages/games/games?gameId=' + that.data.gameId + "&hongBaoHardType=" + that.data.hongBaoHardType + "&hongBaoId=" + that.data.hongBaoId + "&hasPickMoney=" + data.hasPickMoney + "&money=" + data.money + "&msg=" + data.msg
            })
          }
        })
        that.setData({
          randomArrary: [],
          isTransparentShow: true
        })
      }
      setTimeout(function () {
        that.Random();
        that.setData({
          questionNum: ++questionNum,
          isTrue: 'initial'
        })
      }, 1500)
    } else {
      that.playMusic(errorMusicUrl);
      clearInterval(that.data.timer)
      that.setData({
        isTrue: 'error',
        isTransparentShow: true
      })
    }
  },//再试一次
  tryAgain: function (e) {
    this.startGame();
    this.setData({
      count: this.data.count + 1,
      stepCount: 0,
      questionNum: 1,
      isTrue: 'initial',
      isTransparentShow: false,
      randomArrary: []
    })
    this.Random();
    this.timeCount();
  },//放弃答题
  giveUp: function () {
    var that = this;
    this.setData({
      // stepCount:0,
      randomArrary: []
    })
    wx.redirectTo({
      url: '../../pages/games/games?gameId=' + that.data.gameId + "&hongBaoHardType=" + that.data.hongBaoHardType + "&hongBaoId=" + that.data.hongBaoId
    })
  },//倒计时
  timeCount: function () {
    var that = this;
    clearInterval(that.data.timer);
    that.setData({
      timer: setInterval(function () {
        var countDown = that.data.totalTime - 1;
        if (countDown == 3) {
          that.playMusic(countDownMusicUrl);
        }
        that.setData({
          totalTime: countDown
        })
        if (that.data.totalTime < 0) {
          clearInterval(that.data.timer);
          that.setData({
            totalTime: 10,
            tapId: -1,
            isTransparentShow: true,
            isTrue: 'correct'
          })
        }
      }, 1000)
    })
  },//获取数据存入本地
  getData: function () {
    var that = this;
    wx.request({
      url: url + 'questions',
      success: function (res) {
        try {
          wx.setStorageSync('questions', res.data.data.questionList)
          wx.setStorageSync('version', res.data.data.version)
        } catch (e) {
        }
        try {
          var value = wx.getStorageSync('questions')
          var ver = wx.getStorageSync('version')
          if (value) {
            that.setData({
              questionCollect: value,
              version: ver
            })
          }
        } catch (e) {

        }
      }, complete: function () {
        that.Random();
      }
    })
  },//开始游戏
  startGame: function () {
    var that = this;
    wx.request({
      url: url + 'authorized/startGame',
      data: {
        hongBaoId: that.data.hongBaoId,
        tokenKey: that.data.tokenKey,
        token: that.data.token,
        openId: that.data.openId
      },
      success: function (res) {
        var id = res.data.data.id
        that.setData({
          id: id
        })
      }
    })
  },//获取挑战次数
  getCount: function () {
    var that = this;
    wx.request({
      url: url + 'authorized/hongBao',
      data: {
        hongBaoId: that.data.hongBaoId,
        tokenKey: that.data.tokenKey,
        token: that.data.token,
        openId: that.data.openId
      },
      success: function (res) {
        var time = res.data.data.times
        that.setData({
          count: res.data.data.times
        })
      }
    })
  },//是否需要更新题库
  isUpdate: function () {
    var that = this;
    wx.getStorage({
      key: 'version',
      success: function (res) {
        var data = res.data;
        if (data) {
          wx.request({
            url: url + 'questions/needUpdate',
            data: {
              version: data
            },
            success: function (res) {
              if (res.data.data) {
                that.getData()
              }
            }
          })
        }
      }
    })
  },
  onLoad: function (options) {
    var that = this;
    var hongBaoHardType = options.hongBaoHardType;//困难度
    var questionType = options.questionType;//题目类型
    that.setData({
      hongBaoId: options.hongbaoId,
      hongBaoHardType: hongBaoHardType,
      gameId: options.gameId,
      toughType: options.hongBaoHardType,
      questionType: questionType
    })
    var step, toughType;
    if (hongBaoHardType == 'easy') {
      step = 555;
      toughType = 1;
    } else if (hongBaoHardType == 'common') {
      step = 277.5;
      toughType = 2;
    } else if (hongBaoHardType == 'hard') {
      step = 185;
      toughType = 3;
    } else {
      step = 111;
      toughType = 4;
    }
    that.setData({
      step: step,
      toughType: toughType
    })//从本地获取数据
    wx.getStorage({
      key: 'questions',
      success: function (res) {
        var data = res.data;
        if (data) {
          that.setData({
            questionCollect: data
          })
          that.Random();
        }
      },
      fail: res => {
        that.getData();
      }
    })
    that.isUpdate();
    setTimeout(function(){
      that.timeCount();
    },2000)
  },
  onReady: function () {

  },
  onShow: function () {
    var that = this;
    wx.getStorage({
      key: 'loginInfo',
      success: function (res) {
        var data = res.data;
        that.setData({
          tokenKey: data.id,
          token: data.token,
          openId: data.openId
        })
        that.startGame();
        that.getCount();
      }
    })
  },
  onHide: function () {
    wx.stopBackgroundAudio()
    clearInterval(that.data.timer)
  },
  onUnload: function () {
    wx.stopBackgroundAudio()
    clearInterval(that.data.timer)
  },
  playMusic(musicUrl) {
    var backgroundAudioManager = wx.getBackgroundAudioManager()
    backgroundAudioManager.src = musicUrl // 设置了 src 之后会自动播放
  }
})